const express = require('express');
const app = express();
const port = 5557;
const path = require('path');
const query = require('./sql');
const router = require('./router');

app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
    router.index(req, res, {
        title: 'Bt Search'
    });
});

const TYPE = {
    0: ['mp4','rmvb','mov','avi','mpg','mkv','wmv','flv','3gp'],
    1: ['mp3', 'ogg', 'flac', 'wma', 'aac', 'ape', 'rm'],
    2: ['jpg','jpeg','webp','png','bmp','gif'],
    3: ['zip','rar','7z'],
    4: ['txt', 'doc', 'docx'],
    5: ['exe', 'iso', 'ppt', 'pdf']
}
app.get('/search', (req, res) => {
    if(req.query.key) {
        req.query.key = decodeURIComponent(req.query.key);
        let key = req.query.key.split(' ').filter(d => d.length).map(d => `name like '%${d}%'`).join(' or ');
        let page = isNaN(req.query.page) ? 1 : (Number(req.query.page) || 1);
        let size = 20;
        let start = (page - 1) * size;
        let sort = req.query.sort === '0' ? 'asc' : req.query.sort === '1' ? 'desc' : ''
        let type = req.query.type || ''
        if(type) {
            const ext = TYPE[type].map(v => `find_in_set('${v}',extname)`).join(' or ')
            key = `(${key}) and (${ext})`
        }
        let sql = !sort ? 
        `select sql_calc_found_rows * from tb_file where ${key} order by create_time desc limit ${start},${size}` :
        `select sql_calc_found_rows * from tb_file where ${key} order by filesize ${sort} limit ${start},${size}`;
        let options = {data: {}};
        query(sql, (err, results) => {
            if(err) return res.redirect('/');
            options.data.list = results;
            query(`select found_rows() total`, (err, results) => {
               if(err) return res.redirect('/');
               if(!results[0].total && page > 1) return res.redirect(`/search?key=${req.query.key}`);
               options.data.total = results[0].total;
               options.data.page = page;
               options.data.value = req.query.key;
               options.title = req.query.key + ' - Bt Search';
               router.search(req, res, options);
            });
        });
    } else {
        res.redirect('/');
    }
});

app.get('/latest', (req, res) => {
   let sql = `select * from tb_file order by create_time desc limit 0, 100`;
   query(sql, (err, results) => {
       if(err) return res.redirect('/');
       router.latest(req, res, {title: '最新100 - Bt Search', data: {list: results}});
   })
});

app.get('*', (req, res) => {
   res.redirect('/');
});

app.listen(port);